import React from "react";
import ItemTypes from "./ItemTypes";
import { DropTarget, DragSource } from 'react-dnd';

const spec = {
  beginDrag: props => props,
  endDrag: (props, monitor) => {
    const droppedOut = monitor.getItem().field;

    props.onDragEnd(droppedOut);
  }
};
const collect = connect => ({
  connectDragSource: connect.dragSource()
});
const targetSpec = {
  drop: (props, monitor) => {
    const dragging = monitor.getItem().field;
    const dropped = props.field;

    props.onDrop(dragging, dropped);
  },
  hover: (props, monitor) => {
    const dragging = monitor.getItem().field; // 新拖动的组件
    const hovered = props.field; // 被hover的组件

    if (hovered.placeholder) return;

    props.onHover(dragging, hovered);
  }
};
const targetCollect = connect => ({
  connectDropTarget: connect.dropTarget()
});

class Draggable extends React.Component {
  render() {
    const { className, connectDropTarget, connectDragSource, children, onClick } = this.props;

    return (
      connectDropTarget(
        connectDragSource(
          <div className={className} onClick={onClick}>
            {children}
          </div>
        )
      )
    );
  }
}

Draggable = DragSource(ItemTypes.FORMITEM, spec, collect)(Draggable);
Draggable = DropTarget([ItemTypes.FORMITEM], targetSpec, targetCollect)(Draggable);

Draggable.defaultProps = {
  className : '',
  onHover: () => { },
  onDrop: () => { },
  onDragEnd: () => { },
  onClick: () => { }
};

export default Draggable;